import { Breadcrumb as AntdBreadcrumb, BreadcrumbItemProps, BreadcrumbProps } from 'antd';
import { useMemo } from 'react';
import { Link, useMatches } from 'react-router-dom';
import { uniqBy } from 'lodash-es';
import type { ReactNode } from 'react';

// 定义任意对象类型，替代React中不存在的AnyObject
type AnyObject = Record<string, never>;

interface CustomMatch {
  pathname: string;
  handle?: {
    menuName?: ReactNode;
  };
}

// 重新定义面包屑项类型，使用title存储显示内容
type RouteBreadcrumbItem = Omit<BreadcrumbItemProps, 'children' | 'overlay' | 'breadcrumbName'> & {
  path?: string;
  title: ReactNode;
};

// 修正itemRender，从title获取显示内容
const itemRender: BreadcrumbProps<AnyObject>['itemRender'] = (route, _params, routes, paths) => {
  const typedRoute = route as RouteBreadcrumbItem;
  const isLast = routes.indexOf(route) === routes.length - 1;

  const content = typedRoute.title;

  return isLast ? (
    <span>{content}</span>
  ) : (
    <Link to={typedRoute.path ? `/${typedRoute.path}` : `/${paths.join('/')}`}>{content}</Link>
  );
};

function Breadcrumb() {
  const matches = useMatches() as unknown as CustomMatch[];

  const items = useMemo<RouteBreadcrumbItem[]>(() => {
    return uniqBy(matches, 'pathname')
      .filter(match => match.pathname)
      .map(match => ({
        title: match.handle?.menuName || match.pathname,
        path: match.pathname,
      }));
  }, [matches]);

  return <AntdBreadcrumb itemRender={itemRender} items={items} />;
}

export default Breadcrumb;
